<template>
  <view class="home">
    <view class="bg-white" style="overflow: hidden">
      <view
        class="top-main"
        style="
          background-image: url('https://image.zkodoo.cc/25/02/28/16a2727981b6408eb3486926d8268865.png');
        "
      >
        <view
          class="top-fixed"
          style="
            background-image: url('https://image.zkodoo.cc/25/02/28/16a2727981b6408eb3486926d8268865.png');
          "
        >
          <view class="seat"></view>
          <view class="top-nav">
            <view class="logo-name">
              <text v-if="store.state.system.logoText != 0">{{
                store.state.system.logoText
              }}</text>
              <image
                v-else
                :src="logoImage"
                mode="heightFix"
                style="height: 55rpx"
              >
              </image>
            </view>
          </view>

          <my-searchbar
            placeholder="搜索商品名称/条形码"
            v-model="keyword"
            disabled
            @scanCode="onScanCode"
            @replenish="onReplenish"
            @focus="onJumpSearch('search')"
          ></my-searchbar>
        </view>
        <view class="banner-main mt-20">
          <up-swiper
            :list="bannerList"
            keyName="image_url"
            indicator
            indicatorMode="line"
            circular
            @click="onSwiperClick"
            height="320rpx"
            radius="10"
          ></up-swiper>
        </view>
      </view>
      <!-- <view
        class="welcome mt-20"
        style="
          background-image: url('https://image.zkodoo.cc/25/02/28/dc22b5fa7efa427d88f340a8fa38e7e2.png');
        "
      ></view> -->
      <view class="tabs mt-20">
        <view
          v-for="(tab, index) in navbar_list_1"
          :key="index"
          class="tab"
          :style="{ backgroundImage: `url(${tab.image_url})` }"
          @click="onJumpPage(tab)"
        >
          {{ tab.name }}
        </view>
      </view>
      <swiper
        :indicator-dots="true"
        :style="{ height: formatSwiperHeight + 'rpx' }"
        :current="currentSwiper"
        @change="handleSwiperChange"
      >
        <swiper-item v-for="(list, index) in navbar_list_2" :key="index">
          <view class="navbar-main">
            <view
              class="navbar-item-2"
              v-for="(item, index) in list"
              :key="index"
              @click="toCategorize(item)"
            >
              <view class="navbar-icon" v-if="item.image_url">
                <image :src="item.image_url" mode="aspectFill"></image>
              </view>
              <view v-else class="navbar-icon"></view>
              <view class="navbar-name">{{ item.name }}</view>
            </view>
          </view>
        </swiper-item>
      </swiper>
      <!-- <view class="indicator">
				<view :class="['dot', currentSwiper == index ? 'active' : '']" v-for="(list, index) in navbar_list_2"
					:key="index" @click="currentSwiper = index">
				</view>
			</view> -->

      <!-- 活动图-->
      <!--
      <view class="activity-box">
        <image
          class="activity-bg"
          src="https://image.zkodoo.cc/wechat/banner%402x.png"
          mode="heightFix"
        ></image>
      </view>
    -->
      <view class="activity-main" v-if="activityList.length">
        <view
          class="activity"
          v-for="(item, index) in activityList"
          :key="item.id"
        >
          <view class="top">
            <view class="title">
              <view class="text">
                <text>超值特价区</text>
                <text class="en">SALE</text>
              </view>
              <view class="count">
                <my-countdown :endTime="item.end_time"></my-countdown>
              </view>
            </view>
            <view class="more" @click="toActivity(item)">
              更多
              <u-icon name="arrow-right" size="14" color="#999999"></u-icon>
            </view>
          </view>
          <view class="list">
            <view
              class="item"
              v-for="item in item.product_list"
              :key="item.id"
              @click="toActivityGoodsDetail(item.product.id, item.id)"
            >
              <view class="item-content">
                <u-image
                  lazy-load
                  :src="item.product.image_url"
                  width="100%"
                  height="100rpx"
                ></u-image>
                <view class="price">
                  <u-text
                    v-if="$store.state.user.isStore"
                    align="center"
                    mode="price"
                    :text="item.skus[0].amount"
                    size="12"
                    color="#fff"
                  ></u-text>
                  <u-text
                    v-else
                    align="center"
                    text="****"
                    size="12"
                    color="#fff"
                  ></u-text>
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>

    <view class="product-main">
      <view class="product-navbar">
        <view
          class="navbar-item"
          :class="{ active: active == 0 }"
          @click="onProductChange(0)"
        >
          <view class="text">精选</view>
          <view class="sub-text">猜你喜欢</view>
        </view>
        <view
          class="navbar-item"
          :class="{ active: active == 1 }"
          @click="onProductChange(1)"
        >
          <view class="text">收银必备</view>
          <view class="sub-text">经济实惠</view>
        </view>
        <view
          class="navbar-item"
          :class="{ active: active == 2 }"
          @click="onProductChange(2)"
        >
          <view class="text">热销</view>
          <view class="sub-text">爆款热卖</view>
        </view>
        <view
          class="navbar-item"
          :class="{ active: active == 3 }"
          @click="onProductChange(3)"
        >
          <view class="text">本周推荐</view>
          <view class="sub-text">好物榜单</view>
        </view>
      </view>

      <div class="product-list">
        <my-waterfalls :list="productList" gap="20rpx"></my-waterfalls>
        <my-empty
          v-if="productList.length <= 0"
          text="暂无数据"
          marginTop="100rpx"
        ></my-empty>
        <up-loadmore
          v-else
          bg-color="rgb(240, 240, 240)"
          :status="loadStatus"
        ></up-loadmore>
      </div>
    </view>
    <up-popup
      :show="couponPopupShow"
      :safeAreaInsetBottom="false"
      mode="bottom"
      :round="10"
      closeable
      :closeOnClickOverlay="false"
      @close="couponPopupShow = false"
    >
      <view class="p-20">
        <u-text align="center" text="领取优惠券" size="18" bold></u-text>
      </view>
      <view class="p-20">
        <scroll-view scroll-y style="height: 650rpx">
          <my-coupon
            v-for="coupon in notTakeCouponList"
            :key="coupon.id"
            :data="coupon"
          ></my-coupon>
        </scroll-view>
        <u-gap height="10"></u-gap>
        <u-button type="primary" @click="takeAllCoupon">一键领取</u-button>
      </view>
    </up-popup>
    <my-tabbar currentPage="/pages/index/index"></my-tabbar>
  </view>
</template>

<script setup>
import { ref, reactive, onMounted, computed, watch } from "vue";
import { route } from "@/uni_modules/uview-plus";
import { onHide, onPageScroll, onReachBottom, onShow } from "@dcloudio/uni-app";
import {
  goodsList,
  goodsDetail,
  getSubjectList,
  promotionalGoods,
} from "@/common/apis/goods.js";
import { getBannerList } from "@/common/apis/common.js";
import { canNextForStore } from "@/util";
import { useStore } from "vuex";

const store = useStore();

const variantShow = ref(false);
const currentProductId = ref(0);

const currentSwiper = ref(0);

const logoImage = computed(() => {
  return store.state.isFromGlobal
    ? "/static/images/icon/logo_global.png"
    : "/static/images/icon/logo_text.png";
});

const couponPopupShow = ref(false);
const keyword = ref("");
const bannerList = ref([]);
const isShowBg = ref(false);
const isNavFixed = ref(false);
const navbar_list_1 = ref([
  {
    name: "快速补货",
    url: "/pages/index/replenish",
    image_url: "https://image.zkodoo.cc/wechat/tab-ksbh.png",
  },
  {
    name: "促销专区",
    icon: "icon-cuxiaohuodong",
    url: "/pages/goods/activity",
    image_url: "https://image.zkodoo.cc/wechat/tab-cxzq.png",
  },
  {
    name: "折扣专区",
    icon: "icon-zhekou",
    image_url: "https://image.zkodoo.cc/wechat/tab-zkzq.png",
  },
  {
    name: "全部商品",
    url: "/pages/goods/list",
    image_url: "https://image.zkodoo.cc/wechat/tab-qbsp.png",
  },
]);
const active = ref(0);
const productList = ref([]);
const params = reactive({
  page: 1,
  size: 10,
  is_new_recommend: 1, // 新品推荐
});
const totalPage = ref(0);
const loadStatus = ref("nomore");

const waterfallsFlowRef = ref(null);

const navbar_list_2 = computed(() => {
  return chunks(store.getters.formatSubjectList, 10);
});

const formatSwiperHeight = computed(() => {
  if (navbar_list_2.value.length != 0) {
    return Math.ceil(navbar_list_2.value[0].length / 5) * 200;
  }
  return 0;
});

const activityList = ref([]);
const countDown = ref(null);

function onRegisterStore() {
  route({
    url: "pages/app/store",
  });
}

function onSwiperClick() {}

async function onProductChange(val) {
  active.value = val;
  switch (val) {
    case 0:
      params.is_new_recommend = 1;
      delete params.is_week_recommend;
      delete params.is_pos;
      delete params.is_hot;
      break;
    case 1:
      delete params.is_new_recommend;
      delete params.is_week_recommend;
      params.is_pos = 1;
      delete params.is_hot;
      break;
    case 2:
      delete params.is_new_recommend;
      delete params.is_week_recommend;
      delete params.is_pos;
      params.is_hot = 1;
      break;
    case 3:
      delete params.is_new_recommend;
      params.is_week_recommend = 1;
      delete params.is_pos;
      delete params.is_hot;
      break;
  }
  params.page = 1;
  await fetchGoodsList();
}

function toActivity(item) {
  uni.$u.route({
    url: "/pages/goods/activity",
    params: {
      group: item.id,
    },
  });
}

function toActivityGoodsDetail(productId, activityProductId) {
  uni.$u.route({
    url: "/pages/goods/detail",
    params: {
      id: productId,
      activityProductId: activityProductId,
    },
  });
}

async function onJumpPage(row) {
  if (row.url) {
    if (row.url == "/pages/index/replenish") {
      const result = await canNextForStore();
      if (!result) {
        return;
      }
      return uni.redirectTo({
        url: row.url,
      });
    }
    uni.navigateTo({
      url: row.url,
    });
  }
}

function onScanCode() {
  // 调起条码扫描
  uni.scanCode({
    scanType: ["barCode"],
    success: function (res) {
      console.log("条码类型：" + res.scanType);
      console.log("条码内容：" + res.result);
      uni.navigateTo({
        url: "/pages/goods/list?type=search&keyword=" + res.result,
      });
    },
    fail: function (err) {
      console.log(err);
      uni.showToast({
        title: "识别失败",
        icon: "error",
      });
    },
  });
}

function onJumpSearch(type, row) {
  if (type == "search") {
    route({
      url: "/pages/app/search",
    });
  } else if (type == "categorize" && row) {
    route({
      url: "/pages/goods/list",
      params: {
        type: type,
        categorizeId: row.id,
        categorizeName: row.name,
      },
    });
  }
}

// 检测是否为购物车商品
function isCart(id) {
  return Object.keys(checkCart.value).includes(id + "");
}
// 检测商品在购物车中的下标
function checkGoodsIndex(id) {
  let cIndex = 0;
  cartList.value.forEach((item, index) => {
    if (id == item.product.id) {
      cIndex = index;
    }
  });
  return cIndex;
}

// 更改商品数
async function onChangeNum(e, item) {
  let gIndex = checkGoodsIndex(item.id);
  if (e.value < item.min_sale_quantity) {
    uni.showModal({
      title: "删除提示",
      confirmColor: "#f0c785",
      content: `是否确认从购物车中删除此商品?`,
      success: (res) => {
        if (res.confirm) {
          store.dispatch("fetchDelCart", checkCart.value[item.id].cartOrderId);
        } else {
          checkCart.value[item.id].num = item.min_sale_quantity;
        }
      },
    });
  } else if (e.value != checkCart.value[item.id].num) {
    uni.showLoading({
      mask: true,
    });
    const qty =
      e.value > checkCart.value[item.id].num
        ? "+" + item.min_sale_quantity
        : "-" + item.min_sale_quantity;
    await store.dispatch("fetchAddCart", {
      product_id: item.id,
      quantity: qty,
    });
    uni.hideLoading();
  }
}
//加入购物车
function addCart(row) {
  if (row.stock > row.min_sale_quantity) {
    store.dispatch("fetchAddCart", {
      product_id: row.id,
      quantity: row.min_sale_quantity,
    });
  } else {
    uni.$u.toast("库存不足");
  }
}

function chunks(arr, size) {
  const result = [];
  for (let i = 0; i < arr.length; i += size) {
    result.push(arr.slice(i, i + size));
  }
  return result;
}

function toCategorize(item) {
  uni.setStorageSync("currentSubjectId", item.id);
  console.log(uni.getStorageSync("currentSubjectId"));
  uni.redirectTo({
    url: "/pages/index/categorize/categorize",
  });
}

/**
 * @description 获取商品列表
 */
async function fetchGoodsList() {
  if (!params.is_pos) {
    params.subject__in = store.getters.formatSubjectList
      .map((i) => i.id)
      .join(",");
  } else {
    delete params.subject__in;
  }
  const response = await goodsList(params);
  productList.value =
    params.page == 1
      ? response.records
      : productList.value.concat(response.records);
  totalPage.value = response.total_page;
  loadStatus.value = params.page >= response.total_page ? "nomore" : "loadmore";
}

const notTakeCouponList = ref([]);

/**
 * @description 获取未领取的优惠券列表
 * @returns {Promise<void>}
 */
async function getNotTakeCouponList() {
  // 调用 store 中的 action 获取未领取的优惠券列表
  const response = await store.dispatch("fetchNotTakeCouponList");
  // 检查响应是否存在且记录数组不为空
  if (response && response.records.length > 0) {
    // 将未领取的优惠券记录赋值给 notTakeCouponList
    notTakeCouponList.value = response.records.filter((i) => !i.has_get);
    // 如果未领取的优惠券列表不为空，显示优惠券弹窗
    if (notTakeCouponList.value.length) {
      // 显示优惠券弹窗
      couponPopupShow.value = true;
    }
  }
}

async function takeAllCoupon() {
  const promises = [];
  notTakeCouponList.value.forEach((item) => {
    promises.push(store.dispatch("fetchTakeCoupon", item.id));
  });
  await Promise.all(promises);
  couponPopupShow.value = false;
  uni.showToast({
    title: "领取成功",
    icon: "success",
  });
  store.dispatch("fetchCouponList");
}

async function fetchGetBannerList() {
  const response = await getBannerList();
  if (response) {
    bannerList.value = response;
  }
}

async function getActivityGoodsList() {
  const response = await store.dispatch("fetchActivityGoodsList");
  if (response) {
    const promises = {};
    response.forEach((item) => {
      item.product_list = [];
      const now = new Date().getTime();
      const start = new Date(item.start_time.split("-").join("/")).getTime();
      const end = new Date(item.end_time.split("-").join("/")).getTime();
      if (now > start && now < end) {
        promises[item.id] = promotionalGoods({ group: item.id });
      }
    });
    for (let key in promises) {
      const res = await promises[key];
      response.forEach((item) => {
        if (item.id == key) {
          item.product_list = res.records;
        }
      });
    }
    activityList.value = response.filter((i) => i.product_list.length > 0);
  }
}

onMounted(async () => {
  await fetchGetBannerList();
  await fetchGoodsList();
  if (store.state.user.isLogin) {
    await getActivityGoodsList();
  }
  if (store.state.user.isStore) {
    // await getNotTakeCouponList();
  }
});

onShow(async () => {
  if (store.state.user.isLogin) {
    store.dispatch("fetchCartList");
  }
});

onPageScroll((e) => {
  if (e.scrollTop >= 50) {
    isShowBg.value = true;
  } else {
    isShowBg.value = false;
  }
  if (e.scrollTop >= 820) {
    isNavFixed.value = true;
  } else {
    isNavFixed.value = false;
  }
});

const cartList = computed(() => {
  return store.state.cart.list;
});

const checkCart = computed(() => {
  return store.state.cart.checkCart;
});

const storeInfo = computed(() => {
  return store.state.user.storeInfo || "";
});

async function onReplenish() {
  const result = await canNextForStore();
  uni.$u.route({
    url: "/pages/order/replenish",
  });
}

function toCart() {
  uni.redirectTo({
    url: "/pages/index/cart",
  });
}

async function handleOpenVariant(product) {
  const response = await goodsDetail(product.id);
  if (response.skus.length == 0) {
    await store.dispatch("fetchAddCart", {
      product_id: product.id,
      quantity: 1,
      variant_id: product.default_variant.id,
    });
  } else {
    currentProductId.value = product.id;
    variantShow.value = true;
  }
}

function handleSwiperChange(e) {
  currentSwiper.value = e.detail.current;
}

onReachBottom(() => {
  if (loadStatus.value == "nomore") return;
  params.page++;
  fetchGoodsList();
});
</script>

<style lang="scss" scoped>
.home {
  .top-main {
    padding: 0 20rpx;
    height: 620rpx;
    padding-top: 260rpx;
    box-sizing: border-box;
    background-repeat: no-repeat;
    background-size: 100% auto;

    .top-fixed {
      position: fixed;
      top: 0;
      left: 0;
      right: 0;
      padding: 0 20rpx;
      z-index: 20;
      background-repeat: no-repeat;
      background-size: 100% auto;
    }

    .fixed-bottom {
      position: fixed;
      left: 0;
      right: 0;
      top: 280rpx;
      z-index: -10;
      height: 500rpx;
      background-image: linear-gradient(
        to bottom,
        $u-primary,
        rgba(8, 218, 245, 0)
      );
      opacity: 0;
      transition: all ease 1s;

      &.show {
        opacity: 1;
      }
    }

    .top-nav {
      padding-top: 50rpx;
      height: 60rpx;
      display: flex;
      align-items: center;
      margin-bottom: 20rpx;

      .logo-name {
        color: #ffffff;
        font-weight: bold;
        font-size: 28rpx;
      }
    }

    .shop-name {
      color: #000;
      margin-bottom: 10rpx;
    }

    .search-box {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 20rpx;

      .search {
        flex: 1;
        margin: 0 20rpx;
      }

      .search-right {
        display: flex;
        align-items: center;

        .search-right-text {
          width: 48rpx;
          color: #ffffff;
          line-height: 26rpx;
          font-size: 24rpx;
          margin-left: 10rpx;
        }
      }

      .icon {
        width: 60rpx;
        height: 60rpx;
        display: block;
      }
    }

    .top-poster-image {
      width: 100%;
      height: 268rpx;
    }
  }

  .special-offer {
    padding: 0 20rpx;

    image {
      width: 100%;
      height: 288rpx;
      border-radius: 10rpx;
    }
  }

  .banner-main {
    padding: 0 20rpx;
    margin-bottom: 20rpx;
    position: relative;
    z-index: 2;
  }

  .navbar-main {
    margin-top: 20rpx;
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    padding: 0 20rpx;
    margin-bottom: 20rpx;

    .navbar-item-1 {
      padding: 10rpx 0;
      width: calc(100% / 4);
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
    }

    .navbar-item-2 {
      padding: 10rpx 0;
      width: calc(100% / 5);
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
    }

    .navbar-icon {
      width: 110rpx;
      height: 110rpx;
      margin-bottom: 6rpx;

      image {
        width: 100%;
        height: 100%;
        border-radius: 50%;
      }
    }

    .navbar-name {
      font-size: 26rpx;
      color: #333;
    }
  }

  .activity-box {
    width: 100%;
    background-color: #ffffff;
    text-align: center;

    .activity-bg {
      height: 240rpx;
    }
  }

  .p-t126 {
    padding-top: 140rpx !important;
  }

  .product-main {
    // padding-top: 20rpx;
    padding-bottom: 20rpx;
    box-sizing: border-box;
    position: relative;

    .product-navbar {
      display: flex;
      align-items: center;
      justify-content: space-between;
      transition: all ease 0.3s;
      background-color: #fff;
      border-top: 20rpx solid #f0f0f0;
      position: sticky;
      left: 0;
      right: 0;
      top: 240rpx;
      z-index: 10;

      &.navbar-fixed {
        position: fixed;
        left: 0;
        right: 0;
        top: 240rpx;
        z-index: 10;
      }

      .navbar-item {
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        margin: 20rpx 0;
        width: calc(100% / 4);
        text-align: center;
        position: relative;

        &::after {
          content: "";
          position: absolute;
          top: 50%;
          right: 0;
          height: 60rpx;
          width: 2rpx;
          background-color: #f0f0f0;
          transform: translateY(-50%);
        }

        .text {
          margin-bottom: 10rpx;
        }

        .sub-text {
          padding: 0 10rpx;
          color: #666666;
          font-size: 26rpx;
        }

        &.active {
          .text {
            font-size: 28rpx;
            font-weight: bold;
          }

          .sub-text {
            background-color: #2ca544;
            border-bottom-left-radius: 10rpx;
            border-top-right-radius: 10rpx;
            color: #fff;
          }
        }
      }
    }

    .product-list {
      min-height: 800rpx;
      padding: 20rpx;
      background-color: #f0f0f0;
    }
  }

  .minus {
    width: 44rpx;
    height: 44rpx;
    border-width: 1px;
    border-color: #999999;
    border-style: solid;
    border-top-left-radius: 100px;
    border-top-right-radius: 100px;
    border-bottom-left-radius: 100px;
    border-bottom-right-radius: 100px;
    @include flex;
    justify-content: center;
    align-items: center;
  }

  .qty-input {
    text-align: center;
    padding: 0 10px;
    color: #000;
    font-size: 28rpx;
    display: inline-block;
  }

  .plus {
    width: 44rpx;
    height: 44rpx;
    background-color: #3cb9ef;
    border-radius: 50%;
    /* #ifndef APP-NVUE */
    display: flex;
    /* #endif */
    justify-content: center;
    align-items: center;
  }
}

.tabs {
  padding: 20rpx;
  display: flex;
  gap: 10rpx;
  position: relative;
  z-index: 2;

  // &::after {
  //   content: "";
  //   width: 80%;
  //   height: 400rpx;
  //   position: absolute;
  //   left: 50%;
  //   top: -150rpx;
  //   transform: translateX(-50%);
  //   background-image: url("https://image.zkodoo.cc/wechat/welcome.png");
  //   background-position: center center;
  //   background-repeat: no-repeat;
  //   background-size: 100% auto;
  //   z-index: 1;
  // }

  .tab {
    height: 230rpx;
    background-repeat: no-repeat;
    background-size: cover;
    flex: 1;
    text-align: center;
    font-size: 32rpx;
    font-weight: bold;
    padding-top: 20rpx;
    box-sizing: border-box;
  }
}

.indicator {
  margin-top: 10rpx;
  display: flex;
  justify-content: center;
  gap: 20rpx;

  .dot {
    width: 20rpx;
    height: 20rpx;
    border-radius: 20rpx;
    background-color: $u-info;

    &.active {
      background-color: #000;
    }
  }
}

.activity {
  margin: 20rpx;
  padding: 20rpx;
  background-color: #ffdfdf;
  border-radius: 10rpx;

  .top {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20rpx;

    .title {
      display: flex;
      align-items: center;

      .text {
        font-weight: bold;
        font-size: 28rpx;
        font-style: italic;

        .en {
          margin-left: 10rpx;
          color: $u-error;
        }
      }

      .count {
        margin-left: 20rpx;
        // 	font-size: 24rpx;
        // 	margin-left: 20rpx;
        // 	display: flex;
        // 	color: $u-error;

        // 	.time {
        // 		display: flex;

        // 		.num {
        // 			background-color: $u-error;
        // 			padding: 0 10rpx;
        // 			border-radius: 5rpx;
        // 			color: #fff;
        // 		}
        // 	}
      }
    }

    .more {
      color: $u-info;
      display: flex;
      align-items: center;
    }
  }

  .list {
    display: flex;
    flex-wrap: wrap;

    .item {
      width: calc(100% / 5);
      box-sizing: border-box;
      padding: 5rpx;

      .item-content {
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        background-color: #fff;
        padding: 10rpx;
        border-radius: 10rpx;

        .price {
          background-color: $u-error;
          border-radius: 10rpx;
          margin-top: 10rpx;
          padding: 0 10rpx;
        }
      }
    }
  }
}
</style>
